<?php
declare (strict_types=1);

namespace app\admin\middleware;
use auth\Auths;
use think\Response;
use think\facade\Env;
use think\facade\View;
use think\facade\Cookie;
use app\admin\model\SystemParamValue;


/**
 * 登录校验中间件
 * @package app\middleware
 */
class CheckLogin
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
    	//获取描述文件
        $annotation = \base\other\Actions::getMethodDesc();
        // halt(strtolower($annotation['method'] ?? 'all'));
        
        //验证请求方法
		$method = strtolower($annotation['method'] ?? 'all');
		if( $method !='all' && strtolower($request->method()) != $method ){
            return response(View::fetch('../app/providers/errortpl/404'),404);
		}
        //没登录 - 则直接返回登录页
		if( $annotation['global login'] != 'false' ){
            $token = $request->header('x-admin-token') ?: Cookie::get('x-admin-token');
			$refresh_token =  Cookie::get('x-admin-refresh-token');
			if( !$tokens= Auths::instance('admin')->getTokenInfo( $token ) ){
                if( $tokens = Auths::instance('admin')->refreshToken($refresh_token) ){
                    Cookie::set('x-admin-token',$tokens['access_token']);
                    Cookie::set('x-admin-refresh-token',$tokens['refresh_token']);
                }else{
                    if( $request->isAjax() || $request->method() != 'GET'){
                        return \Api::ReError('请登录！',-10);
                    }
                    return response(View::fetch("layout/default"));
                }
			}
		}
		
		//获取用户基本信息
		if( !empty($tokens) ){
			$request->userInfo = $userInfo = $tokens['info'];
			$request->userId = $userInfo['user_id'];
		}
		
        //赋值
		$model = SystemParamValue::where('param_scope','系统基础配置');
		$result = $model->field('param_code as code,param_value as value')->select();
		foreach ($result as $item) {
		    Env::set($item['code'], json_decode($item['value'],true));
		}

		//返回
		return $next($request);
    }
}
